//可使用 express.Router 类创建模块化、可挂载的路由句柄。
var express = require('express');
var router = express.Router();
//ajax
var superagent = require('superagent')

var config = require('../config')
/**
 * 登录认证
 */
router.get('/authentication/login.request',function (req,res,next) {
    //获得参数 get>query post>body
    // var response = {'username':req.query.username,'password':req.query.password}
    if(req.query.username != null && req.query.password != null) {
        superagent.get(config.ServerLocation + ':' + config.ServerPort + '/manager/authentication/login.request')
            .query({username: req.query.username, password: req.query.password})
            .end(function (err, response) {
                if (err) {
                    if(response.status != 200)
                        res.send(JSON.stringify(config.STATUS_FAIL));
                    console.log(err.status + err.message);
                    next();
                }
                else {
                    var cookie = response.header['set-cookie'];//从response中得到cookie
                    res.set('set-cookie', cookie)
                    res.send(JSON.stringify(response.body));
                    next();
                }
            });
    }
    else
    {
        res.send(JSON.stringify(config.STATUS_FAIL));
    }
});

/**
 * 登出
 */
router.post('/authentication/logout.request',function(req,res,next){
    if(req.cookies.authtoken!=null) {
        superagent.post(config.ServerLocation + ':' + config.ServerPort + '/manager/authentication/logout.request')
            .set('Cookie', req.headers.cookie)
            .end(function (err, response) {
                if (err) {
                    if(response.status != 200)
                        res.send(JSON.stringify(config.STATUS_FAIL));
                    console.log(err.status + err.message);
                    next();
                }
                else {
                    res.send(JSON.stringify(response.body));
                    next();
                }
            });
    }else
    {
        res.send(JSON.stringify(config.STATUS_FAIL));
    }
});

/**
 * 获取authToken
 */
router.get('/authentication/getAuthToken',function (req,res,next) {
    //获得参数 get>query post>body
    // var response = {'username':req.query.username,'password':req.query.password}
    if(req.cookies.authtoken!=null) {
        superagent.get(config.ServerLocation + ':' + config.ServerPort + '/manager/authentication/getAuthToken')
            .set('Cookie', req.headers.cookie)
            .end(function (err, response) {
                if (err) {
                    if(response.status != 200)
                        res.send(JSON.stringify(config.STATUS_FAIL));
                    next();
                }
                else {
                    res.send(JSON.stringify(response.body));
                    next();
                }
            });
    }
    else{
        res.send(JSON.stringify(config.STATUS_FAIL));
    }
});


module.exports = router;